<template>
  <div :id="id" class="simple-bar" style="width: 100%; height: 100%;">

  </div>
</template>

<script>
export default {
  name: "SimpleBar",
  props: {
    id: {
      Type: String,
      default: 'simple-bar'
    },
    data: Array,
    title: String,
    subtext: String,
    xAxisData: Array,
    legend: Array
  },
  data() {
    return {
    }
  },
  methods: {
    update() {
      if (!this.chart) {
        this.draw();
        return;
      }
      this.chart.showLoading();
      let option = this.chart.getOption();
      option.series.forEach(item => {
        let target = this.data.find(data => data.name === item.name);
        if (target) {
          item.data = target.data;
        }
      })
      option.legend[0].data = this.legend;
      option.xAxis[0].data = this.xAxisData;
      this.chart.setOption(option);
      this.chart.hideLoading();
    },
    async draw() {
      let that = this;
      setTimeout(() => {
        that.chart = that.$echarts.init(document.getElementById(that.id));
        that.chart.setOption({
          title: {
            text: that.title,
            subtext: that.subtext,
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          toolbox: {
            show: true,
            showTitle: true,
            orient: 'vertical',
            left: 'right',
            top: 'center',
            feature: {
              mark: {
                show: true
              },
              dataZoom: {
                show: true
              },
              // dataView: {show: true, readOnly: false},
              magicType: {
                show: true,
                type: ['line', 'bar', 'stack', 'tiled']
              },
              restore: {
                show: true
              },
              saveAsImage: {
                show: true
              }
            }
          },
          legend: {
            data: that.legend,
            left: '30px'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: that.xAxisData
          },
          yAxis: {
            type: 'value',
            // boundaryGap: [0, 40]
          },
          series: that.data || []
        });
      }, 1000)
    }
  },
  watch: {
    data(value) {
      if (value) {
        this.update();
      }
    }
  }

}
</script>

<style scoped>

</style>
